const Router = require('koa-router');
const bcrypt = require('bcryptjs');
const {Admin: AdminModel} = require('../../model');
const {Admin: AdminValidator} = require('../../validator');
const {LOGIN_ERROR, USER_IS_DISABLED, IMG_CAPTCHA_ERROR} = require('../../ErrorInfo');

const router = new Router({
  prefix: `/api/admin`
});

/**
 * 登录
 */
router.post('/login', async (ctx, next) => {
  const v = await new AdminValidator().scene('login').validate(ctx);

  // 验证码校验
  const {captchaId, verifyCode} = v.get('body');
  const check_captcha = await helper.checkCaptcha(captchaId, verifyCode);
  if (!check_captcha) return helper.fail(IMG_CAPTCHA_ERROR);

  // 验证码校验通过 开始校验账号密码
  const user = await AdminModel.findOne({
    where: {
      username: v.get('body.username')
    }
  });

  // 账号不存在
  if (user === null) return helper.fail(LOGIN_ERROR);

  // 密码错误
  const correct = bcrypt.compareSync(v.get('body.password'), user.password);
  if (!correct) return helper.fail(LOGIN_ERROR);

  // 用户被禁用
  if (user.status === false) return helper.fail(USER_IS_DISABLED);

  // 成功登录
  // 设置返回token信息
  const result = {
    expire: config.jwt.expires * 1000 + new Date().getTime(),
    token: await helper.generateToken({userid: user.id, isAdmin: true}, config.jwt.expires),
    nickname: user.nickname
  };

  // 获取到用户所拥有的所有权限
  const perms = await AdminModel.getPerms(user.id);

  // reddis里再存一份
  await helper.redis.set(`admin:perms:${user.id}`, JSON.stringify(perms), config.jwt.expires);
  await helper.redis.set(`admin:token:${user.id}`, result.token, config.jwt.expires);

  helper.success(result);
});


/**
 * 退出登录
 */
router.post('/logout', async (ctx, next) => {
  await helper.redis.del(`admin:perms:${ctx.decoded.userid}`);
  await helper.redis.del(`admin:token:${ctx.decoded.userid}`);
});

module.exports = router;
